package com.itbaizhan.shopping_order_customer_api.controller;

/**
 * @author spf
 * @date 2024/1/19
 * @time 16:11
 */

import com.itbaizhan.shopping_common.pojo.CartGoods;
import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.result.BaseResult;
import com.itbaizhan.shopping_common.service.CartService;
import com.itbaizhan.shopping_common.service.OrdersService;
import com.itbaizhan.shopping_common.utils.JWTUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.ibatis.annotations.DeleteProvider;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器API
 */
@RestController
@RequestMapping("/user/orders")
public class OrdersController {

    @Reference
    private OrdersService ordersService;
    @Reference
    private CartService cartService;

    /**
     * 新增订单
     * @param token 用户令牌
     * @param orders 订单对象
     * @return 执行结果
     */
    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestHeader String token, @RequestBody Orders orders){
        Long userId = JWTUtil.getId(token);
        orders.setUserId(userId);
        // 添加订单
        Orders orders1 = ordersService.add(orders);
        // 删除redis中的购物车商品数据
        List<CartGoods> cartGoods = orders.getCartGoods();
        for (CartGoods cartGood : cartGoods) {
            cartService.deleteCartOption(userId, cartGood.getGoodId());
        }
        return BaseResult.ok(orders1);
    }

    /**
     * 通过id查询订单
     * @param id 订单id
     * @return 执行结果（orders）
     */
    @GetMapping("/findById")
    public BaseResult<Orders> findById(String id){
        Orders orders = ordersService.findById(id);
        return BaseResult.ok(orders);
    }

    /**
     * 查询用户订单列表
     * @param token 用户令牌
     * @param status 订单状态
     * @return 执行结果
     */
    @GetMapping("/findUserOrders")
    public BaseResult<List<Orders>> findUserOrders(@RequestHeader String token, Integer status){
        Long userId = JWTUtil.getId(token);
        List<Orders> ordersList = ordersService.findUserOrders(userId, status);
        return BaseResult.ok(ordersList);
    }

}
